package cn.ccccltd.waf.message.web;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;

import cn.ccccltd.waf.message.constant.MessageConstants;
import cn.ccccltd.waf.message.init.AppInit;
import cn.ccccltd.waf.message.model.result.MessageResult;
import cn.ccccltd.waf.message.model.vo.Authority;
import cn.ccccltd.waf.message.thread.threadlocal.MessageContext;
import cn.ccccltd.waf.message.util.MessageUtils;

/**
 * 创建日期:2017年11月13日
 * Title: 权限过滤
 * Description：对本文件的详细描述，原则上不能少于50字
 * @author yangjingjiang
 * @mender：（文件的修改者，文件创建者之外的人）
 * @version 1.0
 * Remark：认为有必要的其他信息
 */
@WebFilter(filterName = "securityFilter", urlPatterns = "/*")
@Order(-5)
public class SecurityFilter implements Filter{
	
	private static Logger log = LoggerFactory.getLogger(SecurityFilter.class);
	
	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		
		try {

			log.info("***********过滤器doFilter!*************");
			//判断是否有秘钥
			Object secret = request.getParameter("sendSystemid");
			
			log.info("*************sendSystemid值***********" + secret);
			
			Authority wafMsgAuthority = (Authority)AppInit.userMap.get(secret);
			
			log.info(MessageConstants.LOG_DEBUG_PREFIX + "当前操作系统" +wafMsgAuthority);
			
			if (null == wafMsgAuthority) {
				MessageUtils.writeJsonToPage((HttpServletResponse)response, new MessageResult(MessageConstants.FALSE, MessageConstants.ERR_NOT_PERMISSION, "没有权限访问！"));
			}else {
				MessageContext.setValue(MessageConstants.SESSION, wafMsgAuthority);
				chain.doFilter(request, response);
			}
			
		} finally {
			//处理threadlocal中的值在线程之间传递的处理
            MessageContext.remove();
        }  
		
		
	}

	@Override
	public void destroy() {
		 
	}

}
